package com.kalemao.library.custom.pickerview;

import java.util.Calendar;
import java.util.Date;


import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;

import com.kalemao.library.R;
import com.kalemao.library.custom.pickerview.lib.ScreenInfo;
import com.kalemao.library.custom.pickerview.lib.WheelTime;
import com.kalemao.library.utils.BaseComConst;
import com.kalemao.library.utils.BaseComFunc;

/**
 * 时间选择器
 *
 * @author Sai
 *
 */
public class TimePopupWindow extends PopupWindow implements OnClickListener {
    public enum Type {
        ALL, YEAR_MONTH_DAY, HOURS_MINS, MONTH_DAY_HOUR_MIN, MINS_PER_FIVE, YEAR_MONTH_DAY_WEEK, ONLY_YEAR, YEAR_MONTH, YEAR_MONTH_DAY_AM
    }// 几种选择模式，年月日时分，年月日，时分，月日时分，年月日时分（每五分钟）,年月日周 ，只有年, 年月,年月日上下午

    private View rootView;             // 总的布局
    WheelTime wheelTime;
    private View btnSubmit, btnCancel;
    private View imageView;
    private static final String TAG_SUBMIT = "submit";
    private static final String TAG_CANCEL = "cancel";
    private OnTimeSelectListener timeSelectListener;
    private Type                 type;

    public TimePopupWindow(Context context, Type type,boolean isReport) {
        super(context);
        this.type = type;
        this.setWidth(LayoutParams.FILL_PARENT);
        this.setHeight(LayoutParams.WRAP_CONTENT);
        this.setBackgroundDrawable(new BitmapDrawable());// 这样设置才能点击屏幕外dismiss窗口
        this.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss() {
                if (timeSelectListener != null) {
                    timeSelectListener.onTimeCancel();
                }
            }
        });
        this.setOutsideTouchable(true);
        this.setAnimationStyle(R.style.timepopwindow_anim_style);

        LayoutInflater mLayoutInflater = LayoutInflater.from(context);
        rootView = mLayoutInflater.inflate(R.layout.pw_time, null);
        rootView.setTag(TAG_CANCEL);
        rootView.setOnClickListener(this);
        // -----确定和取消按钮
        btnSubmit = rootView.findViewById(R.id.btnSubmit);
        btnSubmit.setTag(TAG_SUBMIT);
        btnCancel = rootView.findViewById(R.id.btnCancel);
        btnCancel.setTag(TAG_CANCEL);
        btnSubmit.setOnClickListener(this);
        btnCancel.setOnClickListener(this);
        imageView = rootView.findViewById(R.id.pw_time_iamge);
        imageView.setTag(TAG_CANCEL);
        imageView.setOnClickListener(this);
        // ----时间转轮
        final View timepickerview = rootView.findViewById(R.id.timepicker);
        ScreenInfo screenInfo = new ScreenInfo((Activity) context);
        wheelTime = new WheelTime(timepickerview, type);

        wheelTime.screenheight = screenInfo.getHeight();


        // 默认选中当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hours = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        wheelTime.setPicker(year, month, day, hours, minute);
        if (isReport){
            wheelTime.setSTART_YEAR(2018);
            wheelTime.setEND_YEAR(year);
        }else{
            wheelTime.setSTART_YEAR(2017);
            wheelTime.setEND_YEAR(2100);
        }


        setContentView(rootView);
    }

    /**
     * 设置可以选择的时间范围
     *
     * @param START_YEAR
     * @param END_YEAR
     */
    public void setRange(int START_YEAR, int END_YEAR) {
        wheelTime.setSTART_YEAR(START_YEAR);
        wheelTime.setEND_YEAR(END_YEAR);
    }

    public void setStartYear(int startYear) {
        wheelTime.setSTART_YEAR(startYear);
    }

    /**
     * 设置选中时间
     *
     * @param date
     */
    public void setTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        if (date == null)
            calendar.setTimeInMillis(System.currentTimeMillis());
        else
            calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hours = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        wheelTime.setPicker(year, month, day, hours, minute);
    }

    /**
     * 指定选中的时间，显示选择器
     *
     * @param parent
     * @param gravity
     * @param x
     * @param y
     * @param date
     */
    public void showAtLocation(View parent, int gravity, int x, int y, Date date) {
        Calendar calendar = Calendar.getInstance();
        if (date == null)
            calendar.setTimeInMillis(System.currentTimeMillis());
        else
            calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hours = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        wheelTime.setAllYear(false);
        wheelTime.setPicker(year, month, day, hours, minute);
        update();
        super.showAtLocation(parent, gravity, x, y);
        imageView.setBackgroundResource(R.mipmap.mengban);
        imageView.setVisibility(View.VISIBLE);
    }

    public void showAtLocation(View parent, int gravity, int x, int y, Date date, boolean allYear) {
        Calendar calendar = Calendar.getInstance();
        if (date == null)
            calendar.setTimeInMillis(System.currentTimeMillis());
        else
            calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hours = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        wheelTime.setAllYear(allYear);
        wheelTime.setPicker(year, month, day, hours, minute);
        update();
        super.showAtLocation(parent, gravity, x, y);
        imageView.setBackgroundResource(R.mipmap.mengban);
        imageView.setVisibility(View.VISIBLE);
    }

    /**
     * 设置是否循环滚动
     *
     * @param cyclic
     */
    public void setCyclic(boolean cyclic) {
        wheelTime.setCyclic(cyclic);
    }

    @Override
    public void onClick(View v) {
        String tag = (String) v.getTag();
        if (tag.equals(TAG_CANCEL)) {
            imageView.setBackgroundResource(R.color.touming);
            imageView.setVisibility(View.INVISIBLE);
            dismiss();
            if (timeSelectListener != null) {
                timeSelectListener.onTimeCancel();
            }
            return;
        } else {
            if (timeSelectListener != null) {
                // Date date = WheelTime.dateFormat.parse(wheelTime.getTime());
                Date date = BaseComFunc.GetDateByString(wheelTime.getTime(), BaseComConst.DATE_TIME_NOSECOND_FORMAT);
                /**
                 * 这里有个bug，当显示全年的（年，月）类型时，第一次启动进来的时候，默认是选择全年，然后选择一个月，
                 * 这样会导致（非必现）wheelTime.getTime() 获取的值（年）不准。 暂如下处理：手动设置年份
                 */
                date.setYear(wheelTime.getThisYear() - 1900);
                if (type.equals(Type.YEAR_MONTH)) { // 如果是有选择全年的
                    String splitData[] = wheelTime.getTime().split("-");
                    if (splitData.length > 1 && splitData[1].equals("13")) {
                        if (timeSelectListener != null) {
                            timeSelectListener.onTimeAllYearSelect(splitData[0]);
                        }
                    } else {
                        if (timeSelectListener != null) {
                            timeSelectListener.onTimeSelect(date);
                        }
                    }
                } else {
                    if (timeSelectListener != null) {
                        timeSelectListener.onTimeSelect(date);
                    }
                }
            }
            imageView.setVisibility(View.INVISIBLE);
            dismiss();
            return;
        }
    }

    public interface OnTimeSelectListener {
        public void onTimeAllYearSelect(String thisyear); // 显示全年，然后选择的是全年

        public void onTimeSelect(Date date);

        public void onTimeCancel();
    }

    public void setOnTimeSelectListener(OnTimeSelectListener timeSelectListener) {
        this.timeSelectListener = timeSelectListener;
    }

}
